<template>
  <div class="game-details">

    <div class="content">
      <div class="query" v-if="state.type == 1">
        <nut-input v-model="queryGame" :placeholder="t('club_page_ss')" clearable @update:model-value="onClickSearch">
          <template #left>
            <iconpark-icon icon-id="sousuo" size=".8rem" class="refresh"></iconpark-icon>
          </template>
        </nut-input>
      </div>
      <!--  -->
      <div class="main_content" v-if="state.type == 1">
        <scroll-view class="tab" :scroll-y="false" :style="contentStyle()">
          <div v-for="(v, i) in threeGameKinds" :key="i" class="tab_item"
            :class="[state.agentId == v?.id && 'tab_ac', v.id == -1 ? 'noimg' : '']" @click="onClickTab(v)">
            <img v-if="v.id != -1" class="img" v-lazy="joinURL(settings.backend_upload, v.picture_pc)" :key="v.picture_pc"
              alt="" />
            <span class="text">{{ unserialize(v.name, false) }}</span>
          </div>
        </scroll-view>
        <div class="games_box">

          <nut-tabs v-model="state.lableActive" swipeable @change="changeLableTab">
            <nut-tab-pane :title="unserialize(item.kind_name, true)" :pane-key="item.kindId"
              v-for="(item, i) in state.kindList" :key="i">
              <div :style="gameBoxStyle()">

                <nut-infinite-loading v-if="state.hasNext == 1" v-model="infinityValue" :has-more="hasMore"
                  @load-more="onLoad">
                  <!-- <nut-empty v-if="!isLocalLoggedIn && state.lableActive != 0" 
                    :description="t('gameDetail_page_login')"></nut-empty> -->
                  <EmptyState v-if="result.list.length == 0" :text="t('inside_page_no_null_data')" />

                  <div class="game_list" v-else>
                    <div class="item" v-for="(v, i) in result.list" :key="i">
                      <GameItem :item="v" :type="state.type"></GameItem>
                    </div>
                  </div>
                </nut-infinite-loading>
                <div class="game_list" v-else>
                  <EmptyState v-if="result.list.length == 0" :text="t('inside_page_no_null_data')" />

                  <div class="item2" v-else v-for="(v, i) in result.list" :key="i">
                    <GameItem :item="v" :type="3"></GameItem>
                  </div>
                </div>
              </div>
            </nut-tab-pane>
          </nut-tabs>
        </div>
      </div>

      <div v-if="state.type == 2">
        <!-- <nut-tabs v-model="state.lableActive" @change="changeLableTab">
          <nut-tab-pane :title="unserialize(item.kind_name, true)" :pane-key="item.kindId"
            v-for="(item, i) in state.kindList" :key="i">
            <nut-empty v-if="threeGameKinds.length == 0" :description="t('nomore_data')"></nut-empty>
            v-else -->

        <!-- <div class="game_list" v-if="state.kindId == 6">
          <div class="item2" v-for="(v, i) in threeGameKinds" :key="i">

            <GameItem :item="v" :type="3"></GameItem>
          </div>
        </div>
        <div class="game_list" v-else-if="state.kindId == 4">
          <div class="item2 item3" v-for="(v, i) in threeGameKinds" :key="i">

            <GameItem :item="v" :type="3"></GameItem>
          </div>
        </div> -->
        <div class="game_list">
          <div class="item1" v-for="(v, i) in threeGameKinds" :key="i">
            <GameItem :item="v" :type="state.type"></GameItem>
          </div>
        </div>
        <!-- </nut-tab-pane>
        </nut-tabs> -->

      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import { onBeforeMount, reactive, ref, watch, defineAsyncComponent } from "vue";
// import { repMyGamesData } from "@/utils/useNetMethods";
import { storeToRefs } from "pinia";
import { Page } from "@/store/page";
import pinia from "@/store";
import { useI18n } from "vue-i18n";
import { Local } from "@/utils/storage";
import { unserialize } from "@/utils/useStoreMethods";
import { User } from "@/store/user";
import EmptyState from '../searchGames/components/EmptyState.vue'
import { joinURL } from '@/utils/publicMethods'


const GameItem = defineAsyncComponent(() => import("@/components/GameItem.vue"));

const { allCollected, appHeight, isLocalLoggedIn } = storeToRefs(User(pinia));
const route = useRoute();
const { settings, homeGameData } = storeToRefs(Page(pinia));
const contentStyle = () => {
  return window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone ? { height: `calc(${appHeight.value}px - 60vw)` } : { height: `calc(${appHeight.value}px - 50vw)` }
};
const gameBoxStyle = () => {
  return window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone ? { height: `calc(${appHeight.value}px - 76vw)` } : { height: `calc(${appHeight.value}px - 65vw)` }
};
const { t } = useI18n();

const queryGame = ref("");
const infinityValue = ref(false);
const hasMore = ref(true);
const routeQuery = route.query;
console.log(routeQuery, "routeQuery>>>>>>>>>>")
const state = reactive({
  // 是否有下级游戏
  hasNext: 1,
  // 游戏平台id  -1为查看全部的游戏
  agentId: routeQuery?.paneKey ?? -1,

  // 自定义标签 0为全部 1为热门 -2为收藏，-3为最近
  lableId: 0,

  // //也表示场馆id -1 为所有场馆
  kindId: -1,

  // 右上方侧标签点击样式
  lableActive: 0,

  // 所有标签集合
  kindList: [] as any,

  // 当前点击的游戏
  currentGame: null as any,

  // 游戏输入框节流
  timer: null as any,
  // 游戏类型
  type: 1,
});
const params: any = reactive({
  // 参数
  pageSize: 15,
  page: 1,
  isLoad: false
});

const gameList: any = ref([])

const result: any = reactive({
  // 结果
  total_page: 0,
  // 游戏集合
  list: [],
});
const first = {
  kind_name: '{"zh-CN":"全部","vi-VN":"tất cả","en-US":"All"}',
  kindId: 0,
  key: 0,
  icon_after: "/img/game/all_un.webp",
  icon_before: "/img/game/all.webp",

};
const first_hot = {
  kind_name: '{"zh-CN":"热门","vi-VN":"Phổ biến","en-US":"Popular"}',
  kindId: 0,
  key: 0,
  icon_after: "/img/game/all_un.webp",
  icon_before: "/img/game/all.webp",
};
const last = [
  // {
  //   kind_name: "{\"zh-CN\":\"热门\",\"vi-VN\":\"gần đây\",\"en-US\":\"Recent\"}",
  //   kindId: 1,
  //   key: 1,
  //   icon_after: '/img/game/zuijin_un.webp',
  //   icon_before: '/img/game/zuijin.webp'
  // },
  {
    kind_name: '{"zh-CN":"最近","vi-VN":"gần đây","en-US":"Recent"}',
    kindId: -3,
    key: 2,
    icon_after: "/img/game/zuijin_un.webp",
    icon_before: "/img/game/zuijin.webp",
  },
  {
    kind_name: '{"zh-CN":"收藏","vi-VN":"Yêu thích","en-US":"Favorites"}',
    kindId: -2,
    key: 3,
    icon_after: "/img/game/shoucang_un.webp",
    icon_before: "/img/game/shoucang.webp",
  },
];

let gameName = ref("");
let threeGameKinds = ref<any[]>([]);


const getHomeData = () => {
  const data = homeGameData.value.find((e: any) => e.id == Number(state.kindId));
  if (!data) return
  gameName.value = unserialize(data.name, false); // name as string
  if ([3, 4, 6].includes(data.id) && !state.hasNext) {
    state.type = 2;
    threeGameKinds.value = data.three_platform;
    return;
  }
  // const item = data?.find((e: any) => e.name[lang.value].toUpperCase() == gameName.value)
  let a: any = {
    id: -1,
    name: { "zh-CN": "全部", "vi-VN": "tất cả", "en-US": "All" },
    picture_pc: "game_icons/icon_pg.png",
    has_next: 1
  };
  threeGameKinds.value = [a, ...data.three_platform];
  console.log(threeGameKinds.value, "threeGameKinds.value>>>>>>>")
};
watch(() => homeGameData.value, () => {
  getHomeData()
}, { immediate: true })



//切换上方热门标签事件
const changeLableTab = (item: any) => {

  state.lableId = Number(item.paneKey);
  hasMore.value = true;
  state.lableActive = Number(item.paneKey);
  // console.log(item, "item>>>>>>", state.agentId)
  resetData();
  queryData();
};
// TODO 复查协议
// const handleQuery = (res: any) => {
//   result.list = res.info;
//   MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_look_for_game_name, null);
// };
const onClickSearch = () => {
  // if (queryGame.value) {
  //   MessageEvent2.addMsgEvent(
  //     NetMsgType.msgType.msg_notify_look_for_game_name,
  //     handleQuery
  //   );
  //   if (state.timer != null) {
  //     clearTimeout(state.timer);
  //   }
  //   // TODO 复查
  //   state.timer = setTimeout(() => {
  //     let tb = NetPacket.req_look_for_game_name();
  //     tb.agentId = state.agentId;
  //     tb.kindId = state.kindId;
  //     tb.name = queryGame.value;
  //     H5Websocket.sendMessageHandler(tb);
  //   }, 500);
  // }
};

// 点击厂商切换
const onClickTab = (v: any) => {
  if (v.id == 0) {
    state.lableId = 0;
    state.lableActive = -1;
  }
  Local.set("agentId", v.id);
  console.log("v", v, state.lableId);
  gameList.value = []

  if (v.three_game_kind) {
    v.three_game_kind.flatMap((kind: any) => {
      kind.three_game.filter((game: any) => {
        gameList.value.push(game)
      })
    })

  }
  state.hasNext = v.has_next
  state.hasNext = v.has_next
  state.agentId = v.id;

  state.kindList = [];
  resetData();
  getInitData(state.agentId);
  // result.list = []
  if (v.id === -1) {

    if (state.lableId == 0) {
      // result.list = queryData().filter((item: any) => item.is_hot == 1);
    } else {
      if (isLocalLoggedIn.value) {
        gameList.value = queryData()
        // repMyGamesData(handleGamesDetail);
      } else {
        result.list = []
      }
    }
  } else {

    if (state.lableId == 0) {
      result.list = gameList.value.slice(0, 15)
    } else {
      if (isLocalLoggedIn.value) {
        // repMyGamesData(handleGamesDetail);
      } else {
        result.list = []
      }


    }

  }
  console.log(gameList.value, " console.log(gameList.value)??????????")
};

const resetData = () => {
  params.page = 1;
  params.isLoad = false;
  queryGame.value = ''
  hasMore.value = true;
};

const onLoad = () => {


  if (!params.isLoad && state.lableId == 0 && !queryGame.value) {
    params.page++;
    result.list.push(...gameList.value.slice(15 * (params.page - 1), 15 * params.page));
    infinityValue.value = false
    if (result.list.length >= gameList.value.length) {
      hasMore.value = false
    }
  }

};
// 返回游戏列表数据
// const handleGames = (res: any) => {
//   result.list = [...result.list, ...res.info];
//   if (res.info.length < params.pageSize) {
//     hasMore.value = false;
//   }
//   infinityValue.value = false;
//   MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_games_in_platform, null);
// };

const queryData = () => {
  // 查询
  // MessageEvent2.addMsgEvent(
  //   NetMsgType.msgType.msg_notify_get_games_in_platform,
  //   handleGames
  // );
  // const query = NetPacket.req_get_games_in_platform();
  // query.agentId = state.agentId;
  // query.kindId = state.kindId;
  // query.lableId = state.lableId;
  // query.page = params.page;
  // query.pageSize = params.pageSize;
  // H5Websocket.sendMessageHandler(query);
};

const getInitData = (_agentId: any) => {
  state.kindList = [_agentId > 0 ? first : first_hot, ...last];
};

// const queryMyGamesData = (data: any) => {
//   hasMore.value = false
//   const dataSet = new Set(data);  // data 中是字符串类型
//   const arr: any[] = [];
//   gameList.value.filter((itm: any) => {
//     if (dataSet.has(itm.id)) {  // 将 itm.id 转换为字符串
//       arr.push(itm);
//       // console.log(itm, ">>>>>>>>>>>>>>>>> >>>>1");
//       return true;
//     }
//     return false;
//   });
//   result.list = arr
//   if (!result.list.length) {
//     hasMore.value = true
//   }
// }


onBeforeMount(() => {
  const { agent_id, venue_id, has_next } = route.query;
  console.log(route.query, "route.query>>>>>>>>>>", state.type)
  venue_id && (state.kindId = Number(venue_id));
  state.hasNext = Number(has_next) || 1
  getInitData(state.agentId);
  getHomeData()
  if (state.type == 1) {
    let agentId = Local.get("agentId");
    if (agentId) {
      state.agentId = agentId;
    }
    if (agent_id) {
      state.agentId = Number(agent_id);
    }
    // result.list = queryData().filter((item: any) => item.is_hot == 1);
  }
});

watch(
  () => allCollected.value,
  (n: any, o: any) => {
    console.log("n=>" + n, "o=>" + o);
    if (state.lableActive == -2) {
      let gameId = Local.get("gameId");
      result.list = result.list.filter((e: any) => e.id != gameId)
    }

  }
);
</script>

<style scoped lang="scss">
@use './index.scss';
</style>
